import React, { Component } from 'react';
import style from './style';
import { error, DateSelect, RadioGroup, Modal, success, Table } from '../../ui-components';
import { IconFont, Input, tip, InlineButton, LabelInput, Select, Button } from 'sq-ui';
import util from '../../util';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as surveyAction from '../../actions/survey.action';
import moment from 'moment';
import cx from 'classnames'

const status = {
  1: '未开始',
  2: '进行中',
  3: '已结束',
};

export default
@connect(({ survey }) => ({ survey }), dispatch => ({actions: bindActionCreators({ ...surveyAction }, dispatch)}))
class Survey extends Component {

  init_field = {
    question: '',
    description: '',
    lowLabel: '',
    highLabel: '',
    startTime: '',
    endTime: '',
    surveyItemType: 1,
  };

  init_types =  [
    {
      label: '10项选择',
      checked: true,
      value: 1,
    },
    {
      label: '2项选择',
      value: 2,
    },
    {
      label: '文字回答',
      value: 3,
    }
  ];

  state = {
    activeCircle: 4,
    field: this.init_field,
    fre: null,
    updating: false,
    inlineActiveIndex: 0,
    types: this.init_types,
    delItem: null,
    del: false,
    canSubmit: false,
  };

  componentDidMount() {
    this.fetchList();
    this.props.actions.fetchSurveyConfig();
  }

  pageNumber=1
  pageSize=30

  fetchList(props) {
    props = props || this.props;
    const pageNumber = props.location.query.pageNumber || this.pageNumber;
    this.props.actions.fetchSurvey({
      pageNumber,
      pageSize: this.pageSize,
    });
  }

  componentWillUnmount() {
    this.props.actions.resetSurvey();
  }

  componentWillReceiveProps(props) {
    if (!this.props.survey.config && props.survey.config) {
      this.setState({
        fre: props.survey.config.frequency,
      });
    }

    if (this.props.location.query.pageNumber != props.location.query.pageNumber) {
      this.fetchList(props);
    }
  }

  cancelDel = () => {
    this.setState({
      del: false,
      delItem: null,
    });
  };

  update = (name, e) => {
    this.setState({
      field: {
        ...this.state.field,
        [name]: e.target.value,
      }
    }, () => {
      if (name === 'startTime' || name === 'endTime') {
        const { startTime, endTime } = this.state.field;
        if (startTime && endTime) {
          // 测试是否超过三个
          this.props.actions.fetchSamePeriodItems(startTime, endTime, {
            success: (data) => {
              this.setState({
                canSubmit: true,
              });
              if (data.totalNumber > 2) {
                this.setState({
                  over: true,
                });
              } else {
                this.setState({
                  over: false,
                });
              }
            },
            failed: res => {
              this.setState({
                canSubmit: false,
              });
            },
          });
        }
      }
    });
  };

  handleChangeType(value) {
    this.setState({
      field: {
        ...this.init_field,
        lowLabel: value == 2 ? '是': '',
        highLabel: value == 2 ? '否': '',
      },
      types: this.state.types.map(t => {
        if (t.value == value) {
          return {
            ...t,
            checked: true,
          };
        }
        return {
          ...t,
          checked: false,
        };
      })
    });
  }

  updateFre() {
    this.setState({
      updating: true,
    });
    this.props.actions.updateSurveyConfig({
      frequency: this.state.fre,
    }, () => {
      success('更新成功!');
      this.setState({
        updating: false,
      });
    });
  }

  cancelEdit = () => {
    this.setState({canSubmit: false, over: false,edit: false, item: null, field: this.init_field, types: this.init_types});
    this.add = false;
    this.edit = false;
  };

  handleSelectFre(v) {
    this.setState({
      fre: +v + 1,
    });
  }

  handlePageChage(_pageNumber) {
    this.props.router.push({
      pathname: this.props.location.pathname,
      query: {
        ...this.props.location.query,
        pageNumber: _pageNumber,
      }
    });
  }

  disableSubmit() {
    this.setState({
      canSubmit: false,
    });
  }

  enableSubmit() {
    this.setState({
      canSubmit: true,
    });
  }

  render() {
    const { list } = this.props.survey;
    const { totalNumber, surveyItemVOs } = list; 
    const config = {
      pagin: typeof totalNumber === 'number' && {
        pageSize: this.pageSize,
        pageNumber: this.props.location.query.pageNumber || this.pageNumber,
        totalNumber,
        onChange: ::this.handlePageChage,
        fetch: ::this.fetchList,
      },
      data: surveyItemVOs,
      map: {
        range: (_, item) => (
          <span>{util.time(item.startTime)} - {util.time(item.endTime)}</span>
        ),
        status: t => status[t],
        actions: (_, t) => (
          <span data-role="table-hover" className={style['item-actions']}>
            <IconFont value="edit" onClick={() => {
              this.edit = true;
              this.setState({
                edit: true,
                item: t,
                canSubmit: true,
                field: {
                  ...this.state.field,
                  ...t,
                },
                types: this.state.types.map(v => {
                  if (v.value == t.surveyItemType) {
                    return {
                      ...v,
                      checked: true,
                    };
                  }
                  return {
                    ...v,
                    checked: false,
                  };
                }),
              });
            }}/>
            {
              t.deletable ?
              <IconFont onClick={() => {
                this.setState({
                  del: true,
                  delItem: t,
                });
              }} value="delete"/>
              : null
            }
          </span>
        ),
      },
      model: {
        range: '时间范围',
        question: '问题',
        status: '状态',
        actions: '',
      },
      white: true,
    };

    const { config: fre_config } = this.props.survey;

    const surveyType = this.state.item ? this.state.item.surveyItemType : this.state.types.find(t => t.checked).value;
    return (
      <div className={style.root}>
        <header>调研管理</header>
        <section className={style.body}>
          <div>
            <h2>
              <span>调研项目</span>
              <Button
                onClick={() => {
                  this.add = true;
                  this.setState({edit: true});
                }}
                label="添加项目"
                blue
                className={style['add']}
              />
            </h2>
            <Table
              {...config}
            />
          </div>
          <div>
            <h2>调研设置</h2>
            <div className={style.setting}>
              <p>发送频率</p>
              <div
                className={style['select-fre']}
              >
                <Select
                  disabled={!fre_config}
                  list={[
                    '每周',
                    '每两周',
                  ]}
                  onChange={::this.handleSelectFre}
                  value={fre_config ? `${fre_config.frequency-1}`: '-1'}
                  item={
                    (v, i) => (
                      <li
                        data-value={i}
                        key={i}
                      >
                        <span>{v}</span>
                      </li>
                    )
                  }
                />
                {
                  !this.state.fre ? null : (
                    <span>每{this.state.fre == 1 ? '周': '两周'}第一个周五，下午19:00</span>
                  )
                }
              </div>
              <Button
                disabled={this.state.updating}
                onClick={::this.updateFre}
                className={style['update-fre']}
                blue
                label="更新"
              />
            </div>
          </div>
        </section>
        <Modal
          active={this.state.edit}
          className={style.modal}
          onRequestClose={this.cancelEdit}
          isSubmitDisabled={!this.state.canSubmit}
          actions={[
            'cancel',
            () => {

              if (!this.state.field.question.trim()) {
                return;
              }

              const surveyItemType = this.state.types.find(v => v.checked).value;
              const item = {
                ...this.state.field,
                surveyItemType,
              };
              const { startTime, endTime } = item;
              const d = new Date();
              d.setSeconds(0);
              d.setHours(0);
              d.setMilliseconds(0);
              d.setMinutes(0);

              // 创建时
              if (!this.state.item) {
                if (startTime <= d.getTime()) {
                  return error('开始时间应晚于今天!');
                }
                if (endTime <= startTime) {
                  return error('结束时间应晚于开始时间!');
                }
              } 
              // 编辑
              else {
                // 
                if (endTime <= startTime) {
                  return error('结束时间应晚于开始时间!');
                }
                if (endTime <= d.getTime()) {
                  return error('结束时间应晚于今天!');
                }
              }

              // 添加
              if (this.add) {
                this.props.actions.addSurveyItem(item, () => {
                  const { pageNumber } = this.props.location.query;
                  this.pageNumber = 1;
                  if (!pageNumber || pageNumber > 1) {
                    this.handlePageChage(1);
                  } else {
                    this.fetchList();
                  }
                  success('添加成功!');
                });
              }

              // 更新
              else if (this.edit) {
                const {
                  question,
                  description,
                  lowLabel,
                  highLabel,
                  startTime,
                  endTime,
                  surveyItemType,
                } = item;
                this.props.actions.updateSurveyItem(this.state.item.surveyItemId, {
                  question,
                  description,
                  lowLabel,
                  highLabel,
                  startTime,
                  endTime,
                  surveyItemType,
                }, () => {
                  this.fetchList();
                  success('更新成功!');
                });
              }
              this.cancelEdit();
            },
          ]}
          title={this.state.item ? "编辑调研项" : "添加调研项"}
        >
          <div>
            <div>
              <label>调研类型</label>
              <RadioGroup
                disabled={this.state.item}
                className={style.types}
                onChange={::this.handleChangeType}
                name="aa"
                data={this.state.types}
              />
            </div>
            <div className={style['label-input']}>
              <label>调研问题</label>
              <div>
                <Input
                  ref="question"
                  onChange={this.update.bind(null, 'question')}
                  value={this.state.field.question}
                  label="如：从0到10，你对这份工作的满意度如何？"
                  regex={value => value && value.trim()}
                  tip="必填"
                />
              </div>
            </div>
            {
              surveyType == 1 ? (
                <div className={style['label-input']}>
                  <label>补充描述</label>
                  <div>
                    <Input
                      onChange={this.update.bind(null, 'description')}
                      value={this.state.field.description}
                      label="如：1-完全不知道自己的工作目标，工作毫无价值；10-目标非常明确，工作情感爆棚"
                    />
                  </div>
                </div>
              ) : null
            }
            {
              surveyType == 3 ? null : (
                <div className={style['label-two-input']}>
                  <label>{surveyType == 1 ? "标注" : "回答项"} </label>
                  <div>
                    <div>
                      <label style={{color: '#CBD2E1'}}>{surveyType == 1 ? "低分标注" : "肯定回答"}</label>
                      <div>
                        <Input
                          value={this.state.field.lowLabel}
                          onChange={this.update.bind(null, 'lowLabel')}
                        />
                      </div>
                    </div>
                    <div style={{marginLeft: '34px'}}>
                      <label style={{color: '#CBD2E1'}}>{surveyType == 1 ? "高分标注" : "否定回答"}</label>
                      <div>
                        <Input
                          value={this.state.field.highLabel}
                          onChange={this.update.bind(null, 'highLabel')}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              )
            }
            <div className={style['label-two-input']}>
              <label>生效时间</label>
              <div style={{marginTop: '10px'}}>
                <div>
                  <div>
                    {
                      this.state.item ? (
                        <Input
                          disabled
                          defaultValue={this.state.field.startTime && moment(+this.state.field.startTime).format('YYYY-MM-DD')}
                        />
                      ) : (
                        <DateSelect
                          time={this.state.field.startTime && moment(+this.state.field.startTime).format('YYYY-MM-DD')}
                          onChange={value => {
                            this.update.call(this, 'startTime', {target: {value}})
                          }}
                        />
                      )
                    }
                  </div>
                </div>
                <div style={{margin: '5px 10px'}}>到</div>
                <div style={{margin: '0px'}}>
                  <div>
                    <DateSelect
                      time={this.state.field.endTime && moment(+this.state.field.endTime).format('YYYY-MM-DD')}
                      onChange={value => {
                        this.update.call(this, 'endTime', {target: {value}})
                      }}
                    />
                  </div>
                </div>
              </div>
              <p className={style['time-tip']}>为保证填写率，强烈建议控制生效时间，使得同一周期只有1-2个调研项生效中</p>
              {
                this.state.over ? (
                  <div className={style['over-tip']}>按以上设置，该时间范围内将有超过3个调研项同时进行，这可能影响问卷填写率，请留意</div>
                ) : null
              }
            </div>
            <div style={{marginTop: '20px'}}>
              <label>预览</label>
              {
                surveyType === 1 ? (
                  <div className={style.preview}>
                    <p>{this.state.field.question ? this.state.field.question : ''}</p>

                    <div className={style['low-high']} style={{
                      width: '330px',
                      marginLeft: '69px',
                      lineHeight: '1',
                    }}>
                      <span style={{
                        color: '#CBD2E1',
                        fontSize: '12px',
                        display: 'inline-block',
                        minWidth: '24px',
                        textAlign: 'center',
                      }}>{this.state.field.lowLabel}</span>
                      <span style={{
                        float: 'right',
                        color: '#CBD2E1',
                        fontSize: '12px',
                        display: 'inline-block',
                        minWidth: '24px',
                        textAlign: 'center',
                      }}>{this.state.field.highLabel}</span>
                    </div>
                    <div className={style.circles} style={{marginTop: '10px'}}>
                      {
                        [1,1,1,1,1,1,1,1,1,1].map((v, i) => (
                          <span
                            onClick={() => {
                              this.setState({
                                activeCircle: i
                              });
                            }}
                            key={i}
                            className={cx({
                              [style.active]: this.state.activeCircle === i,
                            })}
                          >{i+1}</span>
                        ))
                      }
                    </div>
                    <p className={style.description}>{this.state.field.description || ''}</p>
                    <div className={style.ops}>
                      <input
                        placeholder="补充说几句"
                      />
                    </div>
                  </div>
                ) : surveyType == 2 ? (
                  <div className={style.preview}>
                    <p>{this.state.field.question}</p>
                    <ul className={style['tabs']}>
                      <li className={style.active}>{this.state.field.lowLabel}</li>
                      <li>{this.state.field.highLabel}</li>
                    </ul>
                    <div className={style.ops}>
                      <input
                        placeholder="补充说几句"
                      />
                    </div>
                  </div>
                ) : (
                  <div className={style.preview}>
                    <p>{this.state.field.question}</p>
                    <Input
                      label="补充描述"
                      multi
                      style={{
                        width: "100%",
                        height: "90px",
                        marginTop: "10px",
                      }}
                    />
                  </div>
                )
              }
            </div>
          </div>
        </Modal>
        <Modal
          title="删除调研项"
          onRequestClose={this.cancelDel}
          active={this.state.del}
          actions={[
            'cancel',
            () => {
              this.props.actions.deleteSurveyItem(this.state.delItem.surveyItemId, () => {
                const { pageNumber } = this.props.location.query;
                this.pageNumber = 1;
                if (!pageNumber || pageNumber > 1) {
                  this.handlePageChage(1);
                } else {
                  this.fetchList();
                }
                success('删除成功!');
              });
              this.cancelDel();
            }
          ]}
        >
          <div>确定删除吗?</div>
        </Modal>
      </div>
    );
  }
}
